define(function(require) {
	
	var $ = require("jquery1.7");
	var Confirmbox = require("confirmbox");
	var Validator = require("validator");
	var utils = require("utils");
	var ui = require("ui");
	require("zTree");
	require("ztree-exedit");
	require("ztree-excheck");
	
	var ctx = utils.constants.ctx;
	
	var backManagerService = require("bean/backManagerService");
	
	var layer = layui.layer;
	var form = layui.form;
	var element = layui.element;
	var table = layui.table;
	
	var tablelin = table.render({
	    elem: '#demo'
	    ,url : '/back/base/roleData'
	    ,cols: [[ //标题栏
	      {checkbox: true}
	      ,{field: 'name', title: '角色名称',width: 220}
	      ,{field: '', title: '操作', templet:'#barDemo', width: 300}
	    ]] 
	    ,even: true
	    ,page: true //是否显示分页
	    ,limits: [8, 12, 15,18]
	    ,limit: 8 //每页默认显示的数量
	    ,id: "role_table"
	  });
	
	//重载表格事件
	$(document).on("click","#searchBtn",function(){		
		var param = {
				name:$("#search_input").val()
		}
		tablelin.reload({
			where:param
		});
	})
	$(document).on("click","#addRole",function(){
		$.post(ctx + '/back/base/roleEditUI',function(data){

			layer.open({
				title: '添加角色',
				type:1,
				content:data
			})
			
		})	
	})
	
	$("#deteleRole").bind("click", function(){
	 var checkStatus = layui.table.checkStatus('role_table');
			if (checkStatus.data.length===0) {
				layer.alert("请选择至少一个角色");
				return;
			}
			layer.confirm("确定要删除这些角色？",{icon: 3, title:'提示'},function(isOk){
				if(isOk){
					var data = checkStatus.data;
					var array = [];
					for(var i = 0; i<data.length;i++){
						array.push(data[i].id);   
					}
					if (array.length != 0) {
						try{
							ui.mask().show("请稍候...");
							backManagerService.roleDelete(array);
							ui.mask().hide();
							layer.alert("删除成功",function(){
								
								window.location.reload(true);
							});
						} catch (e) {
							ui.mask().hide();
							layer.alert("删除失败:"+e.message);
						}
					}
				}
			})
	});

	//工具条时间
	table.on('tool(demo)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
		  var layEvent = obj.event; //获得 lay-event 对应的值
		  var data = obj.data;
		  var id = data.id;
		  updateRoleId = parseInt(id);

		  if(layEvent === 'edit'){ //修改身份
			  $.post(ctx + '/back/base/roleEditUI',{"roleId":id}, function(str){
//				  console.log(data.id)
				  layer.open({
				    type: 1,
				    content: str,
				    title:'修改角色'//注意，如果str是object，那么需要字符拼接。
				  });
				  form.render();
				});
			  
		  }else if(layEvent === 'resource'){ 
			  var updateRescourceCb;
			  var role = backManagerService.getRole(updateRoleId);
				if(!role) {
					layer.alert("角色不存在！");
					return;
				}
				var resourseIds = role.resourcesId;
				var data = '<div id="role_resource_tree" class="ztree" style="min-height:160px;"></div>';
		        if(updateRescourceCb == null){
		        	updateRescourceCb = layer.open({
		        		title:'分配权限',
		        		content:data,
		        		yes:function(){
		        			var zTree = $.fn.zTree.getZTreeObj("role_resource_tree");
							var nodes = zTree.getCheckedNodes(true);
							var nodeIds = [];
							for(var i=0; i<nodes.length; i++) {
								nodeIds.push(nodes[i].id);
							}	
							try {

								backManagerService.roleAllotResource(updateRoleId, nodeIds);
								layer.alert('分配成功');
						 		window.location.reload();
						 	} catch (e){
								layer.alert('分配失败！<br/>' + e.message);
						 	}
		        		}
		        	})
		        	
		        }else{
		        
		        }
		        
		        
		        var role_resource_setting = {
						
						data : {
							simpleData :{
								enable :true,
								idKey : "id",
								pIdKey : "parentId" 
							}
							
						},
						check: {
							enable: true,
							chkStyle: "checkbox",
							chkDisabled : false
						},
						async : {
							enable : true,
							url : ctx + "/back/base/resource-json", 
							autoParam : ["id","name"]
						},
						
						view : {
							expandSpeed:"",
							selectedMulti: false		
						},
						edit : {
							enable : true,
							showRemoveBtn:false,
							showRenameBtn:false,
							drag: {
								isCopy: false,
								isMove: false
							}
						},
						callback : { //回调函数  
							onAsyncSuccess: function() {
								ui.mask().hide();
								var zTree = $.fn.zTree.getZTreeObj("role_resource_tree");
								for(var i=0; i < resourseIds.length; i++) {							
									zTree.checkNode(zTree.getNodeByParam("id", resourseIds[i]), true, false);
								}
							}
				        } 
				};
				$.fn.zTree.init($("#role_resource_tree"), role_resource_setting, []);
				ui.mask().show("请稍候...");
		  }
	});
	
	//表单提交
	var IsRun=false;
	form.on('submit(role_sumit)', function(data){
		if(!IsRun){
			 if(data.field.id=="" || data.field.id==null){
				
			    backManagerService.roleAdd(data.field);	
    	 		layer.alert('添加成功',function(){
					
					window.location.reload(true);
				});
			 }else{
				backManagerService.roleUpdate(data.field);
				layer.alert('修改成功',function(){
					
					window.location.reload(true);
				});
			 }
	       location.reload()
		}
		IsRun=true;
	});
	
})